using System;
using System.Collections;
using System.Text;
using UnityEngine;
	
namespace Flaschengeist.DataAccess 
{	
	public class XmlRpc : MonoBehaviour
	{		
		public void Process(string method, Hashtable parameter)
		{
			// Header
			string xml = 	"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
							"\n" + "<methodCall>" +
							"\n" + "<methodName>" + method + "</methodName>" +
							"\n" + "<params>" +
							"\n" + "<param>" +
							"\n" + "<value>" +
							"\n" + "<struct>";
	
			// Parameters
			foreach (DictionaryEntry entry in parameter)
			{
				xml += 		"\n" + "<member><name>" + entry.Key + "</name>" +
							"\n" + "<value><string>" + entry.Value + "</string></value>" +
							"\n" + "</member>";
			}
			
			//Footer
			xml += 			"\n"+ "</struct>" +
							"\n" + "</value>" +
							"\n" + "</param>" +
							"\n" + "</params>" +
		                    "\n" +"</methodCall>";
					
			var enc = Encoding.UTF8;
		    var request = enc.GetBytes(xml);
				
			var www = new WWW(Settings.APPLICATION_SERVER, request);			
			TaskRunner.Instance.Run(DownloadText(www));
		}
		
		private IEnumerator DownloadText(WWW www)
		{
			yield return www;
	
			// check for errors
			if (www.error == null)
			{
				Debug.Log("xml rpc response received: " + www.text);
				Completed(www.text);
			}
			else 
				Debug.Log("WWW Error: "+ www.error);
		}
	
		public event Action<string> Completed = delegate { };
	}
}


